package com.company.Lock;

import java.io.File;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

// 可重入
public class ReentrantDemo {
    static Lock lock = new ReentrantLock();  //可重入锁

    public static void main(String args[]) throws InterruptedException {
        lock.lock();    //当前线程已获取锁
        lock.lock();
        System.out.println(Thread.currentThread() + "get lock 1...");
        lock.unlock();
        lock.unlock();

        new Thread(() -> {
            System.out.println(Thread.currentThread() + " 开始抢锁");
            lock.lock();
            System.out.println(Thread.currentThread() + "我拿到锁啦");
            lock.unlock();
        }).start();

        Thread.sleep(5000);
    }

    /**
     * 文件内所有的文件名增加一个前缀
     *
     * @param dir    文件夹
     * @param prefix 前缀
     */
    public void fileRename(String dir, String prefix) {
        lock.lock();
        try {
            File file = new File(dir);
            File[] files = file.listFiles();
            for (File f : files) {
                if (f.isDirectory()) {
                    fileRename(f.getPath(), prefix);
                } else {
                    file.renameTo(new File("新名字"));
                }
            }
        } finally {
            lock.unlock();
        }
    }
}
